package controllers

import java.io.File

import config.{Global, MyAwait, MyFile, MyRow}
import dao.{GermDao, MapDao}
import javax.inject.Inject
import models.Tables.{AreaRow, LocationRow}
import org.apache.commons.io.FileUtils
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, Action, ControllerComponents}

import scala.concurrent.ExecutionContext

class MapController @Inject()()(germDao: GermDao, mapDao: MapDao, cc: ControllerComponents)
                             (implicit exec: ExecutionContext) extends AbstractController(cc)
  with MyAwait with MyFile with MyRow {


  val loaction = Array("北京", "天津", "上海", "重庆", "河北", "山西", "辽宁", "吉林", "黑龙", "江苏", "浙江", "安徽", "福建",
    "江西", "山东", "河南", "湖北", "湖南", "广东", "海南", "四川", "贵州", "云南", "陕西", "甘肃", "青海",
    "台湾", "内蒙", "广西", "西藏", "宁夏", "新疆", "香港", "澳门")


  def insertMap = Action { implicit request =>
    val germs = germDao.getAllGerm.toAwait
    germs.foreach { x =>
      val l = x.location.split("、").filter(y => loaction.indexOf(y.take(2)) != -1).map { y =>
        val lo = if (y.startsWith("黑龙江") || y.startsWith("内蒙古")) {
          y.trim.take(3)
        } else {
          y.trim.take(2)
        }
        LocationRow(0, lo, x.id)
      }
      val a = x.area.split("、").filter(y => loaction.indexOf(y.take(2)) != -1).map { y =>
        val ar = if (y.startsWith("黑龙江") || y.startsWith("内蒙古")) {
          y.trim.take(3)
        } else {
          y.trim.take(2)
        }
        AreaRow(0, ar, x.id)
      }

      mapDao.insertLocation(l).toAwait
      mapDao.insertArea(a).toAwait
    }

    Ok(Json.toJson("SUCCESS!"))
  }


  def getMapData = Action {
    val json = s"${Global.path}/china.json".readFileToString
    val germ = mapDao.getAllLocation.toAwait.groupBy(_.location).map { case (name, germs) =>
      Json.obj("name" -> name, "value" -> germs.length)
    }.toSeq
    Ok(Json.obj("mapData" -> Json.parse(json), "germ" -> germ))
  }

  def getMapById(id: Int) = Action {
    val lo = mapDao.getLocationByGermId(id).toAwait.map { x =>
      Json.obj("name" -> x.location, "value" -> 1)
    }
    val ar = mapDao.getAreaByGermId(id).toAwait.map { x =>
      Json.obj("name" -> x.location, "value" -> 1)
    }
    val json = s"${Global.path}/china.json".readFileToString
    Ok(Json.obj("mapData" -> Json.parse(json), "location" -> lo, "area" -> ar))
  }

  def getByLocation(location: String) = Action.async {
    mapDao.getByLocation(location.trim).flatMap { x =>
      germDao.getByIds(x).map { y =>
        Ok(Json.toJson(y.map(_.getJsonByT())))
      }
    }
  }


}
